package com.foreveredu.propms.web.struts.action;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.foreveredu.propms.domain.Account;
import com.foreveredu.propms.domain.Bill;
import com.foreveredu.propms.domain.ChargeRecord;
import com.foreveredu.propms.domain.House;
import com.foreveredu.propms.domain.Owner;
import com.foreveredu.propms.domain.SubAccount;
import com.foreveredu.propms.domain.Utilities;
import com.foreveredu.propms.service.IBusinessService;
import com.foreveredu.propms.service.IChargeService;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.ChargeActionForm;
import com.foreveredu.propms.web.util.DigitalUpperCase;

/**
 * 执行物业收费操作
 * @author hushigang
 *
 */
public class ChargeAction extends AbstractBaseDispatchAction {

	private IChargeService chargeService = null;
	private IManagementService managementService = null;
	private IBusinessService businessService = null;
	
	public IChargeService getChargeService() {
		return chargeService;
	}
	
	public void setChargeService(IChargeService chargeService) {
		this.chargeService = chargeService;
	}

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	public IBusinessService getBusinessService() {
		return businessService;
	}

	public void setBusinessService(IBusinessService businessService) {
		this.businessService = businessService;
	}

	// 跳转到物业收费页面
	public ActionForward showCharge(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		return mapping.findForward("showCharge");
	}

	// 显示业主的所有未付账单列表
	public ActionForward showNotPaidBills(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//获得表单数据
		ChargeActionForm caf = (ChargeActionForm)form;
		
		String houseId = caf.getHouseId();
		String ownerName = caf.getOwnerName();
		String phone = caf.getPhone();
		String idCard = caf.getIdCard();
		
		//获得房产编号所对应的房产对象
		House house = null;
		Set<House> houses = new LinkedHashSet<House>();
		if (houseId != null && !houseId.trim().equals("")) {
			house = managementService.findHouseByHouseId(houseId);
			if (house == null) {
				request.setAttribute("houseNotFoundError", "房产编号输入有误，找不到该房产！");
				return mapping.findForward("showCharge");
			}
		} else if (ownerName != null && !ownerName.trim().equals("")) {
			Owner owner = managementService.findOwnerByName(ownerName);
			if (owner == null) {
				request.setAttribute("ownerNameNotFoundError", "业主姓名输入有误，找不到该业主！");
				return mapping.findForward("showCharge");
			}
			//如果业主拥有多处房产，该如何处理？
			houses = owner.getHouses();
		} else if (phone != null && !phone.trim().equals("")) {
			Owner owner = managementService.findOwnerByPhone(phone);
			if (owner == null) {
				request.setAttribute("ownerPhoneNotFoundError", "手机号码输入有误，找不到该业主！");
				return mapping.findForward("showCharge");
			}
			houses = owner.getHouses();
		} else if (idCard != null && !idCard.trim().equals("")) {
			Owner owner = managementService.findOwnerByIdCard(idCard);
			if (owner == null) {
				request.setAttribute("ownerIDCardNotFoundError", "身份证号码输入有误，找不到该业主！");
				return mapping.findForward("showCharge");
			}
			houses = owner.getHouses();
		}
		
		//列出该房产所有未付账单列表
		List<Bill> billList = new ArrayList<Bill>();
		
		//根据房产编号查找物业收费明细
		if (house != null) {
			billList = businessService.findNotPaidBillsOfHouse(house);
		}
		
		if (houses != null && houses.size() > 0) {
			for(House h : houses) {
				billList.addAll(businessService.findNotPaidBillsOfHouse(h));
			}
		}
		
		request.setAttribute("billList", billList);
		//如果账单列表长度大于1，显示合并支付和合并打印链接
		request.setAttribute("size", billList==null?0:billList.size());
		
		StringBuffer ids = new StringBuffer();
		float mergePayAmount = 0;
		if (billList!=null&&billList.size()>1) {
			for(Bill bill : billList) {
				int id = bill.getId();
				ids.append(id+",");
				mergePayAmount += bill.getAmount();
			}
			request.setAttribute("ids", ids.substring(0, ids.length()-1));
			request.setAttribute("mergePayAmount", mergePayAmount);
		}
		
		return mapping.findForward("showNotPaidBills");
	}
	
	// 跳转到房产物业收费明细页面
	public ActionForward search(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//Logger log = Logger.getLogger(ChargeAction.class);
		
		//获得表单数据
		ChargeActionForm caf = (ChargeActionForm)form;
		String billId = caf.getBillId();
		
		//获得该房产某月份的账单
		Bill bill = businessService.findBillById(Integer.parseInt(billId));

		request.setAttribute("bill", bill);
		request.setAttribute("amountUpperCase", DigitalUpperCase.toUpperCase(bill.getAmount()));

		//获得该房产账单中的收费记录列表
		List<ChargeRecord> recordList = businessService.findChargeRecordsByBill(bill);
		request.setAttribute("recordList", recordList);
		
		int isHistoryBill = 1;//历史账单
		int isPreCharged = 0;// 是否已预收物业服务费
		float wantMoney = 0;// 本月应缴纳物业服务费金额

		if (bill.getYear() != 0 && bill.getMonth() != 0) {
			isHistoryBill = 0;//非历史账单
			
			//查询该房产的业主是否在账户中预存物业服务费，并检查物业服务费子账户余额是否足够支付当前物业服务费金额
			Account account = businessService.findAccountByOwner(bill.getHouse().getOwner());
			if (account != null) {
				SubAccount subAccount = businessService.findSubAccountByType(account,1);
				if (subAccount != null) {
					//获得业主物业服务费子账户余额
					float balance = subAccount.getBalance();
					
					//获得该房产本月应缴纳物业服务费金额
					for(ChargeRecord cr: recordList) {
						String itemId = cr.getChargeItem().getItemId();
						if (itemId.equals("1") || itemId.equals("2")) {
							wantMoney = (float) cr.getWantMoney();
						}
					}
					
					//如果子账户余额大于应缴物业服务费金额，则提示用户已预收物业服务费
					if (balance > wantMoney) {
						isPreCharged = 1;
						request.setAttribute("wantMoney", wantMoney);
					}
				}
			}
			request.setAttribute("isPreCharged", isPreCharged);
			
			//获得该房产本月水电使用量
			Utilities utilities = businessService.findUtilitiesByHouseAndDate(bill.getHouse(), bill.getYear(), bill.getMonth());
			float powerBegin = utilities==null?0:utilities.getPowerBegin();
			float powerEnd = utilities==null?0:utilities.getPowerEnd();
			float powerVolume = powerEnd - powerBegin;
			
			float power2Begin = utilities==null?0:utilities.getPower2Begin();
			float power2End = utilities==null?0:utilities.getPower2End();
			float power2Volume = power2End - power2Begin;
			
			float waterBegin = utilities==null?0:utilities.getWaterBegin();
			float waterEnd = utilities==null?0:utilities.getWaterEnd();
			float waterVolume = waterEnd - waterBegin;
		
			float water2Begin = utilities==null?0:utilities.getWater2Begin();
			float water2End = utilities==null?0:utilities.getWater2End();
			float water2Volume = water2End - water2Begin;
			
			request.setAttribute("powerBegin", (int)powerBegin);
			request.setAttribute("powerEnd", (int)powerEnd);
			request.setAttribute("waterBegin", (int)waterBegin);
			request.setAttribute("waterEnd", (int)waterEnd);
			request.setAttribute("powerVolume", (int)powerVolume);
			request.setAttribute("waterVolume", (int)waterVolume);
	
			request.setAttribute("power2Begin", (int)power2Begin);
			request.setAttribute("power2End", (int)power2End);
			request.setAttribute("water2Begin", (int)water2Begin);
			request.setAttribute("water2End", (int)water2End);
			request.setAttribute("power2Volume", (int)power2Volume);
			request.setAttribute("water2Volume", (int)water2Volume);
		}
		request.setAttribute("isHistoryBill", isHistoryBill);
		
		return mapping.findForward("detaislList");
	}

	// 跳转到减免收费申请页面
	public ActionForward reduceChargeReq(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("reduceChargeReq");
	}

	// 跳转到减免收费审核页面
	public ActionForward reduceChargeCheck(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("reduceChargeCheck");
	}

}
